<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('pageTranslation.rMTransfer')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting" style="margin-bottom: 230rpx;">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0 20rpx;">
						<text class="item-info-title" style="padding-right: 40rpx;">{{ $t('fixedAssets.requisition') }}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.receiptCode" type="search"
							@blur="data.focus = false" :focus="data.focus" @confirm="confirmReceipt"
							@iconClick="iconReceiptClick" :disabled="data.disabledReceipt"
							:placeholder="$t('fixedAssets.pleaseRequisition')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title">{{ $t('translationImage.bringUpWarehouse') }}：</text>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.outWarehouseCodeText"
							:placeholder="$t('pageTranslation.defaultLocationBy')" />
					</view>
					<!-- 调入仓库 -->
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title">{{ $t('translationImage.transferredWarehouse') }}：</text>
						<superweiCombox style="text-align:right;" :candidates="data.materialTransferListIn"
							v-if="!data.barcodeList.length" :placeholder="$t('distributedOut.placeholder')"
							:isJSON="true" keyName="value" v-model="data.warehouseText"
							@select="materialTransferSelect"></superweiCombox>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.warehouseText" :placeholder="$t('distributedEnter.placeholderTextChoose')"
							v-else />
					</view>
					<!-- 库位 -->
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('translationImage.transferredSeat') }}：</text>
						<superweiCombox style="text-align:right;" :candidates="data.seatLocation"
							v-if="!data.barcodeList.length" :placeholder="$t('distributedOut.placeholder')"
							:isJSON="true" keyName="value" v-model="data.currentSeat" @select="getClick">
						</superweiCombox>
						<input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
							v-model="data.currentSeat" :placeholder="$t('distributedEnter.placeholderTextChoose')"
							v-else />
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('warehousing.transferType') }}：</text>
						<radio-group @change="radioChange" class="group">
							<label class="uni-list-cell uni-list-cell-pd group-label"
								v-for="(item, index) in data.items" :key="item.value">
								<view class="lable-view">
									<radio :value="item.value" :checked="index === data.current"
										:disabled="data.unSplit" />
								</view>
								<view>{{ item.name }}</view>
							</label>
						</radio-group>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('distributedEnter.barcodeScan') }}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode" type="search"
							@confirm="confirm" @iconClick="iconClick" @focus="data.focus = false" :focus="!data.focus"
							:placeholder="$t('translationImage.pleaseScanTray')">
						</uni-easyinput>
					</view>
				</view>

				<!--推荐扫描条码信息-->
				<view v-if="data.receiptCode&&data.disabledReceipt" class="custom-form-card">
					<uni-collapse>
						<uni-collapse-item titleBorder="none" :show-animation="true" :open="true">
							<template v-slot:title>
								<view class="custom-card-title" style="color:red">
									<text class="title-line"></text>
									{{ $t('fixedAssets.RecommonBarCode') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.barcode')
									}}：</text>{{ data.recommdBarCodeInfo?.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedOut.location')
									}}：</text>{{ data.recommdBarCodeInfo?.location_code }}

								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode')
									}}：</text>{{ data.recommdBarCodeInfo?.material_code }}
								</view>
								<view class="custom-card-itemOne" style="text-align: left;">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('translationImage.numberOfBarcodes')
										}}：</text>{{ data.recommdBarCodeInfo?.barcode_qty }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('fixedAssets.shipQty')
										}}：</text>{{ data.recommdBarCodeInfo?.shouldsend_qty }}
									</view>
								</view>
								<view class="custom-card-itemOne" style="text-align: left;">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('fixedAssets.issuedQty')
										}}：</text>{{ data.recommdBarCodeInfo?.realysend_qty ?? 0 }}
									</view>

									<view class="card-item-50">
										<text class="item-info-title">{{ $t('fixedAssets.stockBatch')
										}}：</text>{{ data.recommdBarCodeInfo?.batch_number }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>

				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<!-- card模块 -->
				<!-- 汇总信息 -->
				<!-- <view class="custom-form-card" v-if="data.list.length" style="margin-bottom: 20rpx;">
						<uni-collapse v-model="data.collect">
							<uni-collapse-item titleBorder="none" :show-animation="true" style="padding-bottom: 20rpx;">
								<template v-slot:title>
									<view class="custom-card-title">
										<text class="title-line"></text>
										{{ $t('materials.summaryOfMaterials') }}
									</view>
								</template>
								<uni-card class="element-auto gui-margin-top card-my">
									<uni-table border stripe emptyText="暂无更多数据"
										style="max-height: 500rpx;box-sizing: border-box;">
										<uni-tr class="tableLineHeight">
											<uni-th class="tableLine" v-for="(x, i) in data.column1" :key="i"
												:width="x.width">{{
													x.label }}</uni-th>
										</uni-tr>
										<uni-tr class="tableLineHeight" v-for="(x, i) in tableData.list" :key="i">
											<uni-td class="tableLine">{{ x.material_code }}</uni-td>
											<uni-td class="tableLine">{{ x.total }}</uni-td>
											<uni-td class="tableLine">{{ x.collect }}</uni-td>
										</uni-tr>
									</uni-table>
								</uni-card>
							</uni-collapse-item>
						</uni-collapse>
					</view> -->
				<!-- 扫描条码的card -->
				<view v-if="data.scanInfo" class="custom-form-card" style="margin-bottom: 120rpx;" >
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCoded')
									}}：</text>{{ data.scanInfo?.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode')
									}}：</text>{{ data.scanInfo?.material_code
										}}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName')
									}}：</text>{{ data.scanInfo?.material_name }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec')
									}}：</text>{{ data.scanInfo?.specification }}
								</view>
								<view class="custom-card-itemOne" style="text-align: left;">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty')
										}}：</text>{{ data.scanInfo?.barcode_qty }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom')
										}}：</text>{{ data.scanInfo?.unit }}
									</view>
								</view>
								<view class="custom-card-itemOne" v-if="data.transferType != 'all'">
									<text class="item-info-title">{{
										$t('warehousing.transferQty') }}：</text>{{ (data.scanInfo?.changeQty || 0) }}
								</view>
								<!-- <view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('translationImage.process') }}：</text>{{data.scanInfo.processCode}}
								</view> -->
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->

				<!-- 底部确定按钮 -->
				<view class="page-bottom-box" style="position: fixed;bottom: 0;left: 0;right: 0;">
					<view class="page-bottomBtn" @click="recommended" style="background-color:#3598DC;color:#fff;">{{
						$t('fixedAssets.recommendedBarcodes') }}</view>
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommit">{{ $t('calendar.submit')
					}}</view>
				</view>
				<!-- 页面弹框 -->
				<uni-popup ref="inputDialog" type="center" :mask-click="false">
					<view class="input-dialog-box">
						<view class="input-dialog-content">
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialCode') }}:{{ data.scanInfo.material_code }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialName') }}:{{ data.scanInfo.material_name }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialSpec') }}:{{ data.scanInfo.specification }}
							</view>
							<view class="input-dialog-item flexclass">
								<view>{{ $t("materials.scanQty") }}：</view>
								<view class="input-dialog-item-count">
									<input v-model="data.inputCurrentQty" type="number"
										:placeholder="$t('distributedEnter.pleaseMaterialQty')" @confirm="qtyInput" />
								</view>
							</view>
						</view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button " @click="cancelFn">
								{{ $t('calendar.cancel') }}
							</view>
							<view class="input-dialog-button dialog-button-left" @click="confirmFn">
								{{ $t('calendar.confirm') }}
							</view>
						</view>
					</view>
				</uni-popup>
				<!-- 调拨的弹框 -->
				<uni-popup ref="inputSplitDialog" type="center" :mask-click="false">
					<view class="input-dialog-box">
						<view class="input-dialog-content">
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialCode') }}:{{ data.scanInfo.material_code }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialName') }}:{{ data.scanInfo.material_name }}
							</view>
							<view class="input-dialog-item">
								{{ $t('distributedEnter.materialSpec') }}:{{ data.scanInfo.specification }}
							</view>
							<view class="input-dialog-item">
								<text class="item-info-title">{{ $t('distributedEnter.qty')
								}}：</text>{{ data.scanInfo.currentQty }}
							</view>
							<view class="input-dialog-item flexclass" style="padding: 20rpx 0;">
								<text class="item-info-title" style="padding-right: 40rpx;"><text
										class="required-color">*</text>{{
											$t('warehousing.transferQty') }}：</text>
								<uni-easyinput class="uni-mt-5" v-model="data.changeQty" type="number"
									:placeholder="$t('hardwareOut.pleaseQty')">
								</uni-easyinput>
							</view>
						</view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button" @click="cancelFnSplit">
								{{ $t('calendar.cancel') }}
							</view>
							<view class="input-dialog-button dialog-button-left" @click="confirmFnSplit">
								{{ $t('calendar.confirm') }}
							</view>
						</view>
					</view>
				</uni-popup>
				<!--部门选择弹框-->
				<uni-popup ref="inputDeptDialog" type="center" :mask-click="false">
					<view class="input-dialog-box">
						<view class="input-dialog-content" style="height: 400rpx">
							<text class="item-info-title">
								<text class="required-color">*</text>{{$t("fixedAssets.transferDepartment")}}：
							</text>
							<uni-data-select v-model="data.deptValue" :localdata="data.deptRange"
								:clear="true"></uni-data-select>
						</view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button" @click="inputDeptDialog.close()">
								{{ $t('calendar.cancel') }}
							</view>
							<view class="input-dialog-button dialog-button-left" @click="confirmDept">
								{{ $t('calendar.confirm') }}
							</view>
						</view>
					</view>

				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import { getDataDictionaryFn, pitchOnFn } from '@/utils/index.js'
import comboGrid from '@/components/comboGrid.vue'
import pdaScan from '@/hooks/pdaScan.js'
import { useStore } from "vuex";
import storageBin from '@/components/storageBin.vue'
import superweiCombox from '@/components/superweiCombox';
import { BIGBARCODER_PRINT } from '@/constant/index.js'
import { materialTransferNew, getIsUsePageSetPDA, scanTransferIn, scanMaterialBarcodeNew, scanReqNo } from '@/api/api.js'
import { USERINFO, OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { onBackPress } from '@dcloudio/uni-app';
import { ref, reactive, onMounted, watch, computed, toRaw } from 'vue';
import tableColor from '@/hooks/tableColor.js'

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

let { tableData } = tableColor();
const { cellStyle, cellHeaderStyle } = tableColor();
let inputDialog = ref(null)
let inputSplitDialog = ref(null)
let inputDeptDialog = ref(null)

components: {
	superweiCombox,
		storageBin,
		comboGrid
}
const storageBinRef = ref(null)
const comboGridRef = ref(null)
let store = useStore();
const { scan } = pdaScan()

let data = reactive({
	defaultValue: '',
	isCapacityBool: false,// 是否带容量 默认为false
	recommdBarCodeInfo: undefined,  //推荐扫码
	receiptCode: '', // 领料单
	disabledReceipt: false, // 领料单扫描是否禁用
	value: ['0'],
	collect: ['0'],
	requestParam: {
		warehouseCode: ''
	},
	deptValue: '', // 选中的部门
	deptRange: [], // 部门的选项
	barcodeList: [],//扫描的条码数组
	locationUseList: [],//
	scanInfo: undefined,
	ignoreLocationCode: [], //前端算满的库位
	materialTransferList: [],//调入仓库数据
	materialTransferListIn: [],
	materialWarehouse: [],//调出仓库数据
	outWarehouseCodeText: 'RM',//'原材料仓'
	outWarehouseCode: '',//'RM'
	outWarehouseName: "",//调出仓库
	warehouseText: '',//调入仓库
	locationId: '',// 调入库位
	warehouseCode: '',//仓库code
	barcode: '', //条码
	currentSeat: '', //调入库位
	seatLocation: [],
	enterWarehouse: '',//调入仓库
	columnRule: {
		column: [{
			label: t('distributedOut.location'),
			name: "locationCode",
		}]
	},
	userInfo: {},
	inputCurrentQty: null,// 特殊条码的数量
	changeQty: 0, //拆分条码数量
	items: [{
		value: 'section',
		name: t('warehousing.partialAllocation'),
		checked: 'true'
	},
	{
		value: 'all',
		name: t('warehousing.fullAllocation')
	}],
	current: 0,
	transferType: 'section',//拆分类型
	splitStatus: false,
	summaryHeight: 'auto',
	list: [],
	column1: [{
		name: 'materialCode',
		label: t('taskList.material'),
		width: 100,
	},
	{
		name: 'total',
		label: t('taskList.scanTotal'),
		width: 100,
	},
	{
		name: 'collect',
		label: t('taskList.materialNumber'),
		width: 80,
	}],
	focus: true,
	isShowFlag: false,
	cancelFlag: false,// 记录是否取消去手动修改调拨类型
	unSplit: false,
	selectAll: [],//后台是部分调拨但是选择了全部调拨的条码集合
})

onMounted(() => {
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
		if (data.focus) {
			getReceipt(itme.code, 'pda')
		}
		if (data.focus == false) {
			getCode(itme.code, 'pda')
		}
	})
	inWarehouse()
})

data.barcodeList = computed(() => {
	return store.state.allotList
})

// 调入仓库获取
const inWarehouse = async () => {
	await getIsUsePageSetPDA({
		warehouseName: '',
		warehouseCode: '',
		size: 20,
		current: 1
	}).then(res => {
		if (res.code == 0) {
			data.materialWarehouse = res.data.records;
			for (let i = 0; i < data.materialWarehouse.length; i++) {
				if (data.materialWarehouse[i].warehouseCode == 'FG' || data.materialWarehouse[i].warehouseCode == 'SP' || data.materialWarehouse[i].warehouseCode == 'RM') {

				} else {
					// console.log('data.materialWarehouse[i]',data.materialWarehouse[i])
					data.materialWarehouse[i].value = data.materialWarehouse[i].warehouseCode
					data.materialTransferListIn.push(data.materialWarehouse[i])
				}
			}
		}
	});
}

// 物料信息汇总 
const collect = () => {
	data.collect = ['0']
	let list = Object.values(data.barcodeList)
	let dataInfo = {};
	list.forEach((item, index) => {
		let { material_code } = item;
		// 扫描的物料按照物料号分类
		if (!dataInfo[material_code]) {
			dataInfo[material_code] = {
				material_code,
				child: []
			}
		}
		dataInfo[material_code].child.push(item)
		// 扫描的物料号分类的总数用量
		dataInfo[material_code].total = dataInfo[material_code].child.reduce((pre, cur) => {
			// 部分调拨
			if (cur.changeQty) {
				return pre + cur.changeQty;
			}
			// 全部调拨
			return pre + cur.currentQty;
		}, 0)
		// 物料条码个数
		dataInfo[material_code].collect = dataInfo[material_code].child.length
	});
	data.list = Object.values(dataInfo);
	tableData.list = data.list
	// console.log(data.list)
}


//把扫描条码变为物料集合的二维数组
watch(() => data.barcodeList, (newVal, oldVal) => {
	console.log('newVal, oldVal', newVal, oldVal)
	// calculateLocationCode(newVal)
	collect()
}, {
	immediate: true,
	deep: true
});

// 选择仓库 取出相对的库位code
const materialTransferSelect = (e) => {
	// console.log(e)
	data.warehouseText = e.value
	data.requestParam.warehouseCode = e.value
	data.warehouseCode = e.value
	data.value = ['0']
	data.ignoreLocationCode = []
	data.locationId = ''
	data.defaultValue = ""
	data.currentSeat = ''
	data.seatLocation = []
	// 通过选择的仓库去查询库位
	scanTransferIn({
		warehouseCode: e.value
	}).then(res => {
		if (res.code == 0) {
			if (res.data.length) {
				res.data.forEach(item => {
					item.label = item.locationCode
					item.value = item.locationCode
					data.seatLocation.push(item)
				})
			}
		}
	})
}

// 获取选中的库位id
const getClick = (x) => {
	console.log(x)
	data.currentLocationInfo = x;
	data.currentSeat = x.value
	data.locationId = x.id;
}

// 扫描 领料单
const iconReceiptClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan()
		getReceipt(code, 'scan')
	}
}
const confirmReceipt = () => {
	getReceipt(data.receiptCode, 'keydown')
}
const getReceipt = (code, type) => {
	data.receiptCode = code
	let parmes = {
		applyCode: code
	}
	scanReqNo(parmes).then(res => {
		if (res.code == 0) {
			data.disabledReceipt = true
			// 扫描领料单后出现第一个推荐条码
			data.recommdBarCodeInfo = res.data
		} else {
			data.receiptCode = ''
			data.focus = true
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	})
}

// 用户点击扫码图标
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击搜索
const confirm = () => {
	getCode(data.barcode, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	data.changeQty = 0
	if (!data.currentLocationInfo) {
		uni.showToast({
			title: t('Common.pleaseSelectLocation'),
			icon: 'none'
		})
		return
	}
	console.log(code, '---code---')
	// 判断这个托盘本次有没有绑定过
	console.log(data.barcodeList, 'data.barcodeList')
	let isBind = data.barcodeList.some(x => x.barcode == code);
	if (isBind) {
		uni.showToast({
			title: t('JsInternational.scanned'),
			icon: 'none'
		})
		return
	}
	if (!data.warehouseText) {
		uni.showToast({
			title: t('pageTranslation.plsChooseWarehous'),
			icon: 'none'
		})
		return
	}
	// 判断当前用户选择的库位有没有容量
	if (data.isCapacityBool && data.ignoreLocationCode.includes(data.locationId)) {
		uni.showToast({
			title: t('JsInternational.volumn'),
			icon: 'none'
		})
		return
	}
	if (!code) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	data.scanValue = code
	let parmes = {
		barcode: code,
		applyCode: data.receiptCode,
		barcodeList:data.barcodeList
	}
	// 扫描 物料条码
	scanMaterialBarcodeNew(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '原材料调拨'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			data.isShowFlag = (!res.data.isPartTransfer) //是否部分调拨
			data.changeQty = Number(res.data.shouldsendQty) //部分调拨，调拨数量赋值默认值为应发数量
			data.recommdBarCodeInfo = res.data.nextBarcode  //下一个推荐扫描的条码

			// 根据后台返回的数据去 判断是否部分调拨
			if (data.isShowFlag) {
				data.transferType = 'all'
				data.current = 1
				data.unSplit = true
			} else {
				data.unSplit = false
				if (data.selectAll.filter(e => e == code)?.length) {
					data.transferType = 'all'
					data.current = 1
					data.selectAll = []  //重置数组
				}
				else {
					data.transferType = 'section'
					data.current = 0
				}
			}

			// 扫码条码成功后执行
			// 判断当前扫描的barcode 是否存在扫描记录里面 如果存在 提示已扫描
			let isBind = data.barcodeList.some(x => x.barcode == res.data.thisBarcode.barcode);
			if (isBind) {
				uni.showToast({
					title: t('pageTranslation.theBarcodeAlready'),
					icon: 'none'
				})
				return
			}
			data.scanInfo = res.data.thisBarcode
			data.scanInfo.currentQty = Number(data.scanInfo.barcode_qty)
			data.scanInfo.goalWarehouseCode = data.outWarehouseCodeText //调出仓库
			data.scanInfo.goalWarehouseName = '原材料仓'
			data.scanInfo.goalLocationCode = data.currentLocationInfo.locationCode //调入库位
			data.scanInfo.goalLocationName = data.currentLocationInfo.locationName //调入名称
			data.scanInfo.newWarehouseCode = data.warehouseText,//调入仓库

				// 添加调拨类型和数量
				data.scanInfo.transferType = data.transferType

			if (data.transferType == 'section') {
				inputSplitDialog.value.open();
				data.splitStatus = true
			} else {
				data.scanInfo.changeQty = data.scanInfo.currentQty
				store.commit('addAllotList', data.scanInfo)
			}
			// // 特殊的4个条码打开弹框
			// if(code=='COVERPLATECARD-CHINA'||code=='PALLETCARD-CHINA'||code=='COVERPLATECARD-USA'||code=='PALLETCARD-USA'){
			// 	inputDialog.value.open();
			// }
			// judgeBarcode()
		} else {
			data.scanInfo = undefined
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

// 弹框的取消按钮
const cancelFn = () => {
	inputDialog.value.close();
	data.scanInfo = undefined
}
// 弹框确定按钮
const confirmFn = () => {
	if (data.inputCurrentQty == null) {
		uni.showToast({
			title: t('Common.pleaseFillInTheBarcode'),
			icon: 'none'
		})
		return
	}
	if (data.inputCurrentQty > Number(data.scanInfo.currentQty)) {
		uni.showToast({
			title: t('Common.theEnteredNumberCannot'),
			icon: 'none'
		})
		return
	}
	data.scanInfo.currentQty = Number(data.inputCurrentQty)
	inputDialog.value.close();
}

// 调拨的弹框确定和取消
const cancelFnSplit = () => {
	inputSplitDialog.value.close();
	data.scanInfo = undefined
}
const confirmFnSplit = () => {
	if (Number(data.changeQty) == null || Number(data.changeQty) <= 0) {
		uni.showToast({
			title: t('Common.pleaseFillInTheBarcode'),
			icon: 'none'
		})
		return
	}
	if (Number(data.changeQty) >= Number(data.scanInfo.currentQty)) {
		uni.showToast({
			title: t('Common.theEnteredNumberCannot'),
			icon: 'none'
		})
		return
	}
	data.scanInfo.changeQty = Number(data.changeQty)
	store.commit('addAllotList', data.scanInfo)
	inputSplitDialog.value.close();
}

// 判断 Barcode
const judgeBarcode = () => {
	let isTrue = data.locationUseList.some(x => x.locationCode === data.locationId)
	if (!isTrue) {
		data.locationUseList.push({
			locationCode: data.currentLocationInfo.locationCode, //库位code
			surplusCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端告诉前端容量
			barcodeList: [], //当前库位本次扫描绑定的barcode条码集合
			currentCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo.usedInventory), //后端容量减去本次扫描绑定条码的剩余容量  前端预算容量
		})
	}
}

// 处理简单生产领料
let matchArr = []
const dealTransferGenerateEasy = async (barcodeList) => {
	// 1.获取数据字典中的简单生产领料料号
	let TransferGenerateEasyList = null;
	await getDataDictionaryFn('TransferGenerateEasy').then(res => {
		if (res.code === 0) {
			TransferGenerateEasyList = res.data?.map(item => item?.value)
		}
	})
	// 2. 找到barcodeList中materialCode存在TransferGenerateEasyList的集合
	let tepData = toRaw(barcodeList);
	matchArr.length = 0;
	tepData.forEach(item => {
		if (TransferGenerateEasyList.includes(item.materialCode) && !item.K3DeptCode) {
			matchArr.push(item)
		}
	});
	// 3.打开一个弹框 绑定部门
	if (matchArr.length === 0) {
		return true
	}
	// 获取部门值集
	data.deptValue = ""; // 重置数据
	await getDataDictionaryFn('Deportment').then(res => {
		if (res.code === 0) {
			res.data.forEach(item => {
				data.deptRange.push(item)
			})
		}
	})
	inputDeptDialog.value.open();
	return false
}

// 保存部门的值
const confirmDept = () => {
	matchArr.forEach(item => item.K3DeptCode = data.deptValue)
	inputDeptDialog.value.close();
	// 重新提交
	handelCommit()
}

// 提交操作
const handelCommit = async () => {
	if (!data.barcodeList.length) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	if (!data.seatLocation) {
		uni.showToast({
			title: t('Common.pleaseSelectLocation'),
			icon: 'none'
		})
		return
	}
	let tepData = toRaw(data.barcodeList)

	let parmes = {
		applyCode: data.receiptCode,
		list: []
	}
	//新添加提交接口的传参数
	let MesInputRecordVoList = []
	let arr = []
	let defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	//新增mesInputProduceRelationVoList参数
	let mesInputProduceRelationVoList = []
	tepData.forEach(x => {
		console.log('return', x)
		parmes.list.push({
			id: x.id,// 条码的id
			barcode: x.barcode,
			printname: defaultValue,
			warehouseCode: x.newWarehouseCode,
			locationCode: x.goalLocationCode,
			outWarehouseCode: x.goalWarehouseCode,
			K3DeptCode: x.K3DeptCode,
			qty: x.changeQty,//拆分数量（调拨数量）
			transferType: x.transferType == 'section' ? 'PartTransfer' : 'AllTransfer'//拆分类型（调拨类型）
		});
		MesInputRecordVoList.push({
			barCode: x.barcode,
			materialCode: x.materialCode,
			operatorName: data.userInfo.userName,
			operatorNo: data.userInfo.userNameId,
			processCode: x.processCode,
			processName: x.processName,
			qty: Number(x.currentQty),
			sourceLocationCode: x.locationCode,
			sourceWarehouseCode: x.warehouseCode,
			targetLocationCode: x.goalLocationCode,
			targetWarehouseCode: x.goalWarehouseCode
		})
		mesInputProduceRelationVoList.push({
			inputBarcode: x.barcode,
			materialCode: x.materialCode,
			operatorName: data.userInfo.userName,
			operatorNo: data.userInfo.userNameId,
			processCode: x.processCode,
			processName: x.processName,
			qty: Number(x.currentQty),
			sourceLocationCode: x.locationCode,
			sourceWarehouseCode: x.warehouseCode,
			targetLocationCode: x.goalLocationCode,
			targetWarehouseCode: x.goalWarehouseCode
		})
		// parmes.mesInputRecordVoList = MesInputRecordVoList
		// parmes.mesInputProduceRelationVoList = mesInputProduceRelationVoList

	});
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	//提交接口
	materialTransferNew(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '原材料调拨'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.code == 0) {
			tepData.forEach(x => {
				if (Number(x.changeQty) > 0) {
					store.commit('addAllotListSplit', x)
				}
			})
			//隐藏加载框
			uni.hideLoading();
			//删除已提交的数据
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			store.commit('reactAllotList')
			// 清空数据
			// data.outWarehouseCodeText=''
			data.outWarehouseName = "";
			data.warehouseText = "";
			data.defaultValue = "";
			data.barcode = "";
			data.currentSeat = ''
			data.inputCurrentQty = null;  //特殊条码数量置为0
			data.changeQty = 0
			data.scanInfo = undefined
			data.receiptCode = ""
			data.disabledReceipt = false
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
			return
		}
	});
}

const radioChange = (evt) => {
	// console
	for (let i = 0; i < data.items.length; i++) {
		if (data.items[i].value === evt.detail.value) {
			data.current = i;
			console.log(data.items[i])
			data.transferType = data.items[i].value

			if (data.transferType == 'all') {  //选择的是全部调拨
				if (data.barcode != null && data.barcode != "") {
					data.selectAll.push(data.barcode)
				}
			}
			else {
				data.selectAll = []
			}
			console.log(data.transferType == 'all')
			break;
		}
	}
}

// 推荐条码
const recommended = () => {

	if (!data.receiptCode) {
		uni.showToast({
			title: t('fixedAssets.requisitionAnd'),
			icon: 'none'
		})
		return
	}
	navigate({
		url: '/pages/barcodeManagement/allowBarcode?reqNo=' + data.receiptCode
	})
}
//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/barcodeManagement/allocationMaterialNewRecord'
	})
}

// 返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.barcodeList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					store.commit('reactAllotList')
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.clearedIfReturned'),
		success: function (res) {
			if (res.confirm) {
				store.commit('reactAllotList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
	margin-bottom: 110rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0px;
	bottom: 0px;
	width: 100%;
}

.item-color {
	color: #000;
	font-weight: bold;
}

.group {
	display: flex;
	flex-direction: row;

	.group-label {
		width: 230rpx;
		display: flex;
		flex-direction: row;
	}

	.lable-view {
		width: 70rpx;
		height: 100%;
	}
}

.zb-table .item-td {
	height: 60rpx !important;
}

.queryMessage_list {
	height: 120rpx;
	width: 100%;
	overflow: hidden;

	&_card {
		color: rgb(107, 105, 105);
		letter-spacing: 4rpx;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		border-bottom: 2rpx dashed #cecece;
	}

	.queryMessage_list_div {
		width: 100%;
		height: 60rpx;
		display: flex;
		flex-direction: row;
		text-align: left;
	}

	&_frist {
		// width: 50%;
		background-color: #fff;
		display: flex;
		flex-direction: row;
	}

	&_tow {
		// width: 50%;
		background-color: #fff;
		display: flex;
		flex-direction: row;
	}

	&_three {
		// width: 100%;
		// display: block;
		background-color: #fff;
		display: flex;
		flex-direction: row;
	}

	&_title {
		height: 60rpx;
		width: auto;
		font-size: 26rpx;
		text-align: center;
		line-height: 60rpx;
		letter-spacing: 2rpx;
		padding: 0 20rpx 0 20rpx;
		box-sizing: border-box;
	}

	&_spec {
		height: 60rpx;
		flex: 1 1 auto;
		font-size: 20rpx;
		text-align: left;
		line-height: 60rpx;
	}
}

.tableLineHeight {
	height: 60rpx;
	min-width: 630rpx !important;
}

.tableLine {
	padding: 0 20rpx !important;
	box-sizing: border-box;
}

.uni-table-loading {
	height: 60rpx !important;
}
</style>
